// API基础配置
const API_BASE_URL = 'http://118.31.223.190:8080';

// 通用API请求函数
class ApiClient {
    constructor() {
        this.baseURL = API_BASE_URL;
    }

    async request(url, options = {}) {
        const isForm = options && options.body instanceof FormData;
        const headers = isForm ? (options.headers || {}) : { 'Content-Type': 'application/json', ...(options.headers || {}) };
        const config = { headers, ...options };

        try {
            const response = await fetch(`${this.baseURL}${url}`, config);
            const data = await response.json();
                
                if (!response.ok) {
                    const error = new Error(data.message || `HTTP error! status: ${response.status}`);
                    error.response = response;
                    error.data = data;
                    throw error;
                }
                
                return data;
            } catch (error) {
                console.error('API请求失败:', error);
                // 添加更详细的错误信息输出
                console.error('请求URL:', `${this.baseURL}${url}`);
                console.error('请求选项:', options);
                // 如果是网络错误，提供更友好的错误信息
                if (error instanceof TypeError && error.message === 'Failed to fetch') {
                    console.error('网络连接失败，请检查服务器是否正常运行');
                }
                throw error;
            }
        }

    async get(url, params = {}) {
        const queryString = new URLSearchParams(params).toString();
        const fullUrl = queryString ? `${url}?${queryString}` : url;
        return this.request(fullUrl, { method: 'GET' });
    }

    async post(url, data = {}) {
        if (data instanceof FormData) {
            return this.request(url, { method: 'POST', body: data });
        }
        return this.request(url, { method: 'POST', body: JSON.stringify(data) });
    }

    async put(url, data = {}) {
        return this.request(url, {
            method: 'PUT',
            body: JSON.stringify(data)
        });
    }

    async delete(url) {
        return this.request(url, { method: 'DELETE' });
    }
}

// 创建API客户端实例
const api = new ApiClient();

// 用户管理API
const UserAPI = {
    // 用户登录
    login: (loginData) => api.post('/api/users/login', loginData),
    
    // 创建用户
    createUser: (userData) => api.post('/api/users', userData),
    
    // 更新用户
    updateUser: (userData) => api.put('/api/users', userData),
    
    // 删除用户
    deleteUser: (userId) => api.delete(`/api/users/${userId}`),
    
    // 获取用户详情
    getUserById: (userId) => api.get(`/api/users/${userId}`),
    
    // 分页查询用户
    pageUsers: (page = 1, size = 10, keyword = '') => 
        api.get('/api/users/page', { page, size, keyword }),
    
    // 修改密码
    changePassword: (userId, oldPassword, newPassword) => 
        api.put('/api/users/password', null, {
            params: { userId, oldPassword, newPassword }
        }),
    
    // 重置密码
    resetPassword: (userId) => api.put(`/api/users/reset-password/${userId}`)
};

// 图书管理API
const BookAPI = {
    // 创建图书
    createBook: (bookData) => api.post('/api/books', bookData),
    
    // 更新图书
    updateBook: (bookData) => api.put('/api/books', bookData),
    
    // 删除图书
    deleteBook: (bookId) => api.delete(`/api/books/${bookId}`),
    
    // 获取图书详情
    getBookById: (bookId) => api.get(`/api/books/${bookId}`),
    
    // 根据ISBN获取图书
    getBookByIsbn: (isbn) => api.get(`/api/books/isbn/${isbn}`),
    
    // 分页查询图书
    pageBooks: (page = 1, size = 10, keyword = '', categoryName = '') => 
        api.get('/api/books/page', { page, size, keyword, categoryName }),
    
    // 上传图书封面
    uploadImage: (file) => {
        const formData = new FormData();
        formData.append('file', file);
        return api.post('/api/books/uploadImage', formData);
    },
    
    // 增加图书库存
    increaseStock: (bookId, count) => 
        api.post(`/api/books/${bookId}/increase-stock`, null, {
            params: { count }
        }),
    
    // 减少图书库存
    decreaseStock: (bookId, count) => 
        api.post(`/api/books/${bookId}/decrease-stock`, null, {
            params: { count }
        })
};

// 图书分类管理API
const BookCategoryAPI = {
    // 创建分类
    createCategory: (categoryData) => api.post('/api/book-categories', categoryData),
    
    // 更新分类
    updateCategory: (categoryData) => api.put('/api/book-categories', categoryData),
    
    // 删除分类
    deleteCategory: (categoryId) => api.delete(`/api/book-categories/${categoryId}`),
    
    // 获取分类详情
    getCategoryById: (categoryId) => api.get(`/api/book-categories/${categoryId}`),
    
    // 获取所有分类
    getAllCategories: () => api.get('/api/book-categories')
};

// 借阅管理API
const BorrowAPI = {
    // 借书
    borrowBook: (borrowData) => api.post('/api/borrows', borrowData),
    
    // 还书
    returnBook: (borrowId) => api.post(`/api/borrows/${borrowId}/return`),
    
    // 续借
    renewBook: (borrowId, days) => 
        api.post(`/api/borrows/${borrowId}/renew?days=${days}`)
            .catch(error => {
                console.error('续借失败:', error);
                throw error;
            }),
    
    // 标记为逾期
    markAsOverdue: (borrowId) => api.post(`/api/borrows/${borrowId}/overdue`),
    
    // 标记为丢失
    markAsLost: (borrowId) => api.post(`/api/borrows/${borrowId}/lost`),
    
    // 支付罚款
    payFine: (borrowId) => api.post(`/api/borrows/${borrowId}/pay-fine`),
    
    // 获取借阅详情
    getBorrowById: (borrowId) => api.get(`/api/borrows/${borrowId}`),
    
    // 分页查询借阅记录（过滤空参数，避免后端400）
    pageBorrows: (page = 1, size = 10, userId = '', status = '', keyword = '') => {
        const params = { page, size };
        if (userId !== '' && userId !== null && userId !== undefined) params.userId = userId;
        if (status !== '' && status !== null && status !== undefined) params.status = status;
        if (keyword !== '' && keyword !== null && keyword !== undefined) params.keyword = keyword;
        return api.get('/api/borrows/page', params);
    },
    
    // 获取用户当前借阅
    getCurrentBorrows: (userId, page = 1, size = 10) => 
        api.get('/api/borrows/current', { userId, page, size }),
    
    // 获取逾期借阅
    getOverdueBorrows: (page = 1, size = 10) => 
        api.get('/api/borrows/overdue', { page, size })
};

// 支付管理API
const PaymentAPI = {
    // 创建支付记录
    createPayment: (paymentData) => api.post('/api/payments', paymentData),
    
    // 完成支付
    completePayment: (paymentId, payMethod) => 
        api.post(`/api/payments/${paymentId}/complete`, null, {
            params: { payMethod }
        }),
    
    // 取消支付
    cancelPayment: (paymentId) => api.post(`/api/payments/${paymentId}/cancel`),
    
    // 获取支付详情
    getPaymentById: (paymentId) => api.get(`/api/payments/${paymentId}`),
    
    // 分页查询支付记录
    pagePayments: (page = 1, size = 10, userId = '', type = '', status = '') => 
        api.get('/api/payments/page', { page, size, userId, type, status }),
    
    // 获取用户支付总额
    getUserPaymentTotal: (userId) => api.get(`/api/payments/user/${userId}/total`),
    
    // 处理借阅罚款支付
    handleBorrowFinePayment: (borrowId, payMethod) => 
        api.post(`/api/payments/borrow/${borrowId}/fine`, null, {
            params: { payMethod }
        })
};

// 费用管理API
const FeeAPI = {
    // 计算逾期罚款
    calculateOverdueFee: (userId) => api.get('/api/fees/overdue', { userId }),
    
    // 计算损坏赔偿
    calculateDamageFee: (userId, bookId, damageRatio) => 
        api.get('/api/fees/damage', { userId, bookId, damageRatio }),
    
    // 计算丢失赔偿
    calculateLostFee: (userId, bookId, lostRatio = 1.0) => 
        api.get('/api/fees/lost', { userId, bookId, lostRatio }),
    
    // 获取用户费用记录
    getUserFeeRecords: (userId, params = {}) => api.get(`/api/fees/user/${userId}`, params),
    
    // 获取用户费用统计
    getUserFeeStats: (userId) => api.get(`/api/fees/user/${userId}/stats`),
    
    // 支付费用
    payFee: (feeId, payMethod) => api.post(`/api/fees/${feeId}/pay?payMethod=${payMethod}`)
};

// 图书条目管理API
const BookItemAPI = {
    // 获取图书的所有条目
    getBookItems: (bookId) => api.get(`/api/book-items/book/${bookId}`),
    
    // 根据状态获取图书条目
    getBookItemsByStatus: (bookId, status) => 
        api.get(`/api/book-items/book/${bookId}/status/${status}`),
    
    // 获取可借阅的图书条目
    getAvailableBookItems: (bookId, count = 1) => 
        api.get(`/api/book-items/book/${bookId}/available`, { count }),
    
    // 更新图书条目状态
    updateBookItemStatus: (itemId, status, remark) => 
        api.put(`/api/book-items/${itemId}/status`, null, {
            params: { status, remark }
        }),
    
    // 批量更新图书条目状态
    batchUpdateBookItemStatus: (updateData) => 
        api.put('/api/book-items/batch/status', updateData),
    
    // 获取图书条目状态统计
    getBookItemStatusCount: (bookId) => 
        api.get(`/api/book-items/book/${bookId}/status-count`),
    
    // 获取状态选项
    getStatusOptions: () => api.get('/api/book-items/status-options')
};

// 通知管理API
const NotificationAPI = {
    // 创建通知
    createNotification: (notificationData) => {
        console.log('发送通知请求:', notificationData);
        return api.post('/api/notifications', notificationData)
            .catch(error => {
                console.error('创建通知失败:', error);
                throw error;
            });
    },
    
    // 创建系统通知
    createSystemNotification: (notificationData) => {
        console.log('发送系统通知请求:', notificationData);
        return api.post('/api/notifications/system', notificationData)
            .catch(error => {
                console.error('创建系统通知失败:', error);
                throw error;
            });
    },
    
    // 标记通知为已读
    markAsRead: (notificationId) => {
        // 确保notificationId是有效值
        if (notificationId === undefined || notificationId === null || notificationId <= 0) {
            const error = new Error('通知ID不能为空');
            console.error('标记已读失败:', error.message);
            return Promise.reject(error);
        }
        console.log('标记通知为已读请求:', notificationId);
        return api.post(`/api/notifications/${notificationId}/read`)
            .catch(error => {
                console.error('标记已读失败:', error);
                throw error;
            });
    },
    
    // 批量标记通知为已读
    batchMarkAsRead: (notificationIds) => {
        console.log('批量标记通知为已读请求:', notificationIds);
        return api.post('/api/notifications/batch/read', notificationIds)
            .catch(error => {
                console.error('批量标记已读失败:', error);
                throw error;
            });
    },
    
    // 标记用户所有通知为已读
    markAllAsRead: (userId) => {
        if (userId === undefined || userId === null || userId <= 0) {
            const error = new Error('用户ID不能为空');
            console.error('标记所有通知为已读失败:', error.message);
            return Promise.reject(error);
        }
        console.log('标记用户所有通知为已读请求:', userId);
        return api.post(`/api/notifications/user/${userId}/read-all`)
            .catch(error => {
                console.error('标记所有通知为已读失败:', error);
                throw error;
            });
    },
    
    // 删除通知
    deleteNotification: (notificationId) => {
        // 确保notificationId是有效值
        if (notificationId === undefined || notificationId === null || notificationId <= 0) {
            const error = new Error('通知ID不能为空');
            console.error('删除通知失败:', error.message);
            return Promise.reject(error);
        }
        console.log('删除通知请求:', notificationId);
        return api.delete(`/api/notifications/${notificationId}`)
            .catch(error => {
                console.error('删除通知失败:', error);
                throw error;
            });
    },
    
    // 获取通知详情
    getNotificationById: (notificationId) => {
        // 确保notificationId是有效值
        if (notificationId === undefined || notificationId === null || notificationId <= 0) {
            const error = new Error('通知ID不能为空');
            console.error('获取通知详情失败:', error.message);
            return Promise.reject(error);
        }
        console.log('获取通知详情请求:', notificationId);
        return api.get(`/api/notifications/${notificationId}`)
            .catch(error => {
                console.error('获取通知详情失败:', error);
                throw error;
            });
    },
    
    // 分页查询用户通知（过滤空参数并规范 isRead）
    pageUserNotifications: (page = 1, size = 10, userId = '', type = '', isRead = '') => {
        const params = { page, size };
        if (userId !== '' && userId !== null && userId !== undefined) params.userId = userId;
        if (type !== '' && type !== null && type !== undefined) params.type = type;
        if (isRead !== '' && isRead !== null && isRead !== undefined) {
            if (typeof isRead === 'string') {
                const lower = isRead.toLowerCase();
                if (lower === 'true' || lower === 'false') params.isRead = lower === 'true';
            } else if (typeof isRead === 'boolean') {
                params.isRead = isRead;
            }
        }
        console.log('分页查询通知请求:', params);
        return api.get('/api/notifications/page', params)
            .catch(error => {
                console.error('分页查询通知失败:', error);
                throw error;
            });
    },
    
    // 获取用户未读通知数量
    countUnreadNotifications: (userId) => {
        if (userId === undefined || userId === null || userId <= 0) {
            const error = new Error('用户ID不能为空');
            console.error('获取未读通知数量失败:', error.message);
            return Promise.reject(error);
        }
        console.log('获取用户未读通知数量请求:', userId);
        return api.get(`/api/notifications/user/${userId}/unread-count`)
            .catch(error => {
                console.error('获取未读通知数量失败:', error);
                throw error;
            });
    }
};

// 系统配置API
const SystemConfigAPI = {
    // 获取配置值
    getConfigValue: (configKey) => api.get(`/system/config/${configKey}`),
    
    // 设置配置值
    setConfigValue: (configKey, configValue, description = '') => 
        api.post('/system/config/set', null, {
            params: { configKey, configValue, description }
        }),
    
    // 批量设置配置
    batchSetConfig: (configMap) => api.post('/system/config/batch', configMap),
    
    // 删除配置
    deleteConfig: (configKey) => api.delete(`/system/config/${configKey}`),
    
    // 获取所有配置
    getAllConfigs: () => api.get('/system/config/all')
};

// 统计API
const StatisticsAPI = {
    // 获取仪表板统计数据
    getDashboardStats: () => api.get('/api/statistics/dashboard'),
    
    // 获取财务统计数据
    getFinancialStats: () => api.get('/api/statistics/financial'),
    
    // 获取借阅趋势
    getBorrowTrend: (days = 30) => 
        api.get('/api/statistics/borrow-trend', { days }),
    
    // 获取图书分类统计
    getCategoryStats: () => api.get('/api/statistics/category-stats'),
    
    // 获取财务趋势
    getFinancialTrend: (days = 30) => 
        api.get('/api/statistics/financial-trend', { days }),
    
    // 获取热门图书排行
    getPopularBooks: (limit = 10) => 
        api.get('/api/statistics/popular-books', { limit }),
    
    // 获取活跃用户排行
    getActiveUsers: (limit = 10) => 
        api.get('/api/statistics/active-users', { limit }),
    
    // 获取借阅状态分布
    getBorrowStatusStats: () => api.get('/api/statistics/borrow-status-stats'),
    
    // 获取用户角色分布
    getUserRoleStats: () => api.get('/api/statistics/user-role-stats'),
    
    // 获取新增用户数量（最近7天）
    getNewUsersCount: () => api.get('/api/statistics/new-users-count'),
    
    // 获取活跃用户数量（最近7天有借阅记录）
    getActiveUsersCount: () => api.get('/api/statistics/active-users-count')
};

// 工具函数
const Utils = {
    // 默认封面地址
    defaultImage: () => {
        // 优先使用映射目录下默认图
        return '/images/default-goods.png';
    },
    // 显示加载状态
    showLoading: () => {
        const loadingOverlay = document.getElementById('loadingOverlay');
        if (loadingOverlay) {
            loadingOverlay.classList.add('active');
        }
    },

    // 隐藏加载状态
    hideLoading: () => {
        const loadingOverlay = document.getElementById('loadingOverlay');
        if (loadingOverlay) {
            loadingOverlay.classList.remove('active');
        }
    },

    // 显示消息提示
    showMessage: (message, type = 'info', duration = 3000) => {
        const messageContainer = document.getElementById('messageContainer');
        if (!messageContainer) return;

        const messageEl = document.createElement('div');
        messageEl.className = `message ${type}`;
        
        const iconMap = {
            success: 'fas fa-check-circle',
            error: 'fas fa-exclamation-circle',
            warning: 'fas fa-exclamation-triangle',
            info: 'fas fa-info-circle'
        };

        messageEl.innerHTML = `
            <i class="${iconMap[type] || iconMap.info}"></i>
            <span>${message}</span>
            <button class="message-close" onclick="this.parentElement.remove()">
                <i class="fas fa-times"></i>
            </button>
        `;

        messageContainer.appendChild(messageEl);

        // 自动移除消息
        setTimeout(() => {
            if (messageEl.parentElement) {
                messageEl.remove();
            }
        }, duration);
    },

    // 格式化日期
    formatDate: (dateString) => {
        if (!dateString) return '-';
        const date = new Date(dateString);
        return date.toLocaleDateString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit'
        });
    },

    // 格式化金额
    formatMoney: (amount) => {
        if (amount === null || amount === undefined) return '¥0.00';
        return `¥${parseFloat(amount).toFixed(2)}`;
    },

    // 获取状态文本
    getStatusText: (status, type = 'user') => {
        const statusMap = {
            user: {
                1: '正常',
                0: '禁用'
            },
            borrow: {
                1: '借阅中',
                2: '已归还',
                3: '逾期'
            },
            payment: {
                1: '待支付',
                2: '已支付',
                3: '已取消'
            },
            notification: {
                1: '到期提醒',
                2: '预约通知',
                3: '系统公告'
            }
        };
        return statusMap[type]?.[status] || status;
    },

    // 获取角色文本
    getRoleText: (role) => {
        const roleMap = {
            'system_admin': '系统管理员',
            'book_admin': '图书管理员',
            'normal_user': '普通用户'
        };
        return roleMap[role] || role;
    },

    // 创建分页组件
    createPagination: (currentPage, totalPages, onPageChange) => {
        const pagination = document.createElement('div');
        pagination.className = 'pagination';

        // 上一页按钮
        const prevBtn = document.createElement('button');
        prevBtn.textContent = '上一页';
        prevBtn.disabled = currentPage <= 1;
        prevBtn.onclick = () => onPageChange(currentPage - 1);
        pagination.appendChild(prevBtn);

        // 页码按钮
        const startPage = Math.max(1, currentPage - 2);
        const endPage = Math.min(totalPages, currentPage + 2);

        if (startPage > 1) {
            const firstBtn = document.createElement('button');
            firstBtn.textContent = '1';
            firstBtn.onclick = () => onPageChange(1);
            pagination.appendChild(firstBtn);

            if (startPage > 2) {
                const ellipsis = document.createElement('span');
                ellipsis.textContent = '...';
                ellipsis.style.padding = '0.5rem';
                pagination.appendChild(ellipsis);
            }
        }

        for (let i = startPage; i <= endPage; i++) {
            const pageBtn = document.createElement('button');
            pageBtn.textContent = i;
            pageBtn.className = i === currentPage ? 'active' : '';
            pageBtn.onclick = () => onPageChange(i);
            pagination.appendChild(pageBtn);
        }

        if (endPage < totalPages) {
            if (endPage < totalPages - 1) {
                const ellipsis = document.createElement('span');
                ellipsis.textContent = '...';
                ellipsis.style.padding = '0.5rem';
                pagination.appendChild(ellipsis);
            }

            const lastBtn = document.createElement('button');
            lastBtn.textContent = totalPages;
            lastBtn.onclick = () => onPageChange(totalPages);
            pagination.appendChild(lastBtn);
        }

        // 下一页按钮
        const nextBtn = document.createElement('button');
        nextBtn.textContent = '下一页';
        nextBtn.disabled = currentPage >= totalPages;
        nextBtn.onclick = () => onPageChange(currentPage + 1);
        pagination.appendChild(nextBtn);

        return pagination;
    },

    // 验证表单
    validateForm: (formData, rules) => {
        const errors = {};
        
        for (const [field, rule] of Object.entries(rules)) {
            const value = formData[field];
            
            if (rule.required && (!value || value.trim() === '')) {
                errors[field] = rule.message || `${field}不能为空`;
                continue;
            }
            
            if (rule.pattern && !rule.pattern.test(value)) {
                errors[field] = rule.message || `${field}格式不正确`;
                continue;
            }
            
            if (rule.minLength && value.length < rule.minLength) {
                errors[field] = rule.message || `${field}长度不能少于${rule.minLength}个字符`;
                continue;
            }
            
            if (rule.maxLength && value.length > rule.maxLength) {
                errors[field] = rule.message || `${field}长度不能超过${rule.maxLength}个字符`;
                continue;
            }
        }
        
        return errors;
    }
};

// 导出API和工具函数
window.UserAPI = UserAPI;
window.BookAPI = BookAPI;
window.BookCategoryAPI = BookCategoryAPI;
window.BookItemAPI = BookItemAPI;
window.BorrowAPI = BorrowAPI;
window.PaymentAPI = PaymentAPI;
window.FeeAPI = FeeAPI;
window.NotificationAPI = NotificationAPI;
window.SystemConfigAPI = SystemConfigAPI;
window.StatisticsAPI = StatisticsAPI;
window.Utils = Utils;